package com.sh.caryr.erp.custmz;

import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

import com.sh.caryr.erp.entity.user.User;
import com.sh.caryr.erp.util.ERPConstants;
import com.sh.caryr.erp.util.UtilityTool;

public class LayoutContainer {

    public static Map<String, Layout> defaultLayouts = new HashMap<String, Layout>();

    public static final String LAYOUT_SEARCH_DIS_FLDS = "searchDisFlds";
    public static final String LAYOUT_TAB_DIS_FLDS = "tableDisFld";
    public static final String LAYOUT_FORM_DIS_FLDS = "formDisFlds";
    public static final String LAYOUT_FORM_EDIT_FLDS = "formEditFlds";

    static {
        /*************** User & User Role *****************/
        defaultLayouts.put(ERPConstants.AUTH_TARGET_USER, getUserLayout());
        defaultLayouts.put(ERPConstants.AUTH_TARGET_USERROLE, getRoleLayout());

        /*************** Shop *****************/
        defaultLayouts.put(ERPConstants.AUTH_TARGET_SHOP, getShopLayout());

        /*************** Material / MaterialComb / Stock  *****************/
        defaultLayouts.put(ERPConstants.AUTH_TARGET_MATERIAL, getMaterialLayout());
        defaultLayouts.put(ERPConstants.AUTH_TARGET_MATERIAL_COMB, getMaterialCombLayout());
        defaultLayouts.put(ERPConstants.AUTH_TARGET_STOCK, getStockLayout());
        defaultLayouts.put(ERPConstants.AUTH_TARGET_STOCK_HIS, getStockHisLayout());
        defaultLayouts.put(ERPConstants.AUTH_TARGET_COMBSTOCK, getProductCombStockLayout());
        /*************** Product *****************/
        defaultLayouts.put(ERPConstants.AUTH_TARGET_PRODUCT, getProductLayout());
        defaultLayouts.put(ERPConstants.AUTH_TARGET_PROMAPPING, getProductMappingLayout());
        /*************** Sales Order *****************/
        defaultLayouts.put(ERPConstants.AUTH_TARGET_SO, getOrderSalLayout());
        defaultLayouts.put(ERPConstants.AUTH_TARGET_SO_HIS, getOrderSalHisLayout());

        /*************** Basic Setting *****************/
        defaultLayouts.put(ERPConstants.AUTH_TARGET_SYSTEMLOG, getSystemLogLayout());

        /*************** XXXX To delete XXXX *****************/
        defaultLayouts.put(ERPConstants.AUTH_TARGET_PROCOMB, getProductCombLayout());
        defaultLayouts.put("orderPurch", getOrderPurchLayout());
        defaultLayouts.put("orderPurchHis", getOrderPurchHisLayout());
        defaultLayouts.put(ERPConstants.AUTH_TARGET_SOMAPPING, getSOMappingLayout());
    }

    public static void main(String arg[]) throws UnsupportedEncodingException {
    }

    public static Layout getLayout(String clsName, User user) {
        Layout layout = defaultLayouts.get(clsName);
        UserAuthorityContainer authCont = new UserAuthorityContainer(user);
        return filterByAuth(clsName, layout, user, authCont);
    }

    public static Layout getLayout(String clsName) {
        return defaultLayouts.get(clsName);
    }

    private static Layout filterByAuth(String clsName, Layout layout, User user, UserAuthorityContainer authCont) {
        Layout filteredLayout = new Layout();

        String fieldStr = layout.get(LAYOUT_SEARCH_DIS_FLDS);
        String fields[] = null;
        fields = filterByAuth(clsName, fieldStr, user, authCont);
        if (fields != null) {
            filteredLayout.searchDisFld = fields;
        }
        fieldStr = layout.get(LAYOUT_TAB_DIS_FLDS);
        fields = filterByAuth(clsName, fieldStr, user, authCont);
        if (fields != null) {
            filteredLayout.tableDisFld = fields;
        }
        fieldStr = layout.get(LAYOUT_FORM_DIS_FLDS);
        fields = filterByAuth(clsName, fieldStr, user, authCont);
        if (fields != null) {
            filteredLayout.formDisFld = fields;
        }

        fieldStr = layout.get(LAYOUT_FORM_EDIT_FLDS);
        fields = filterByAuth(clsName, fieldStr, user, authCont);
        if (fields != null) {
            filteredLayout.formEditFld = fields;
        }
        return filteredLayout;
    }

    private static String[] filterByAuth(String clsName, String fieldStr, User user, UserAuthorityContainer authCont) {
        if (fieldStr == null || "".equals(fieldStr)) {
            return null;
        }
        StringBuffer temp = new StringBuffer();
        String[] fields = fieldStr.split(",");
        for (String field : fields) {
            if (user.getIsSuperuser() == ERPConstants.ENITYT_ACTIVE ||
                    (authCont.check(clsName, ERPConstants.AUTH_ACTVT_READ, ERPConstants.AUTH_FIELD_FIELD, field))) {
                temp.append(field).append(",");
            }
        }
        if (temp.length() != 0) {
            return temp.substring(0, temp.length() - 1).split(",");
        } else {
            return null;
        }

    }

    /******************Set Default Layouts ******************************/
    private static Layout getUserLayout() {
        Layout layout = new Layout();
        String fieldStr = "id,name,coco,subcoco,phone,userRole";
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        fieldStr = "id,name,password,coco,subcoco,phone,userRole";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);
        fieldStr = "id,name,password,coco,subcoco,email,phone,address,userRole";
        layout.put(LAYOUT_FORM_EDIT_FLDS, fieldStr);
        fieldStr = "id,name,password,coco,subcoco,email,phone,address,userRole,createdAt";
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        return layout;
    }

    private static Layout getProductCombLayout() {
        Layout layout = new Layout();
        String fieldStr = "id,name,coco,subcoco,description";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        return layout;
    }

    private static Layout getMaterialCombLayout() {
        Layout layout = new Layout();
        String fieldStr = "id,name,coco,subcoco,description";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        layout.put(LAYOUT_FORM_EDIT_FLDS, fieldStr);
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        return layout;
    }


    private static Layout getMaterialLayout() {
        Layout layout = new Layout();
        String fieldStr = "id,name,coco,subcoco,shortDesc,stock";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);
        fieldStr = "id,name,coco,subcoco,shortDesc,stock,createdBy,createdAt";
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        fieldStr = "id,name,coco,subcoco,shortDesc,stock";
        layout.put(LAYOUT_FORM_EDIT_FLDS, fieldStr);
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        return layout;
    }

    private static Layout getProductCombStockLayout() {
        Layout layout = new Layout();
        String fieldStr = "id,coco,subcoco,name,description";
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        fieldStr = "id,coco,subcoco,name,description,stock";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        layout.put(LAYOUT_FORM_EDIT_FLDS, fieldStr);
        return layout;
    }

    private static Layout getProductLayout() {
        Layout layout = new Layout();
        String fieldStr = "img,name,code,type,status,salePrice";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);

        fieldStr = "coco,subcoco,materialId,materialCombId,serialNo,name,brand,shortDesc,description,stock,purchasePrice,costPrice,"
                + "supplyPrice,salePrice,salesChannel,packaging,length,width,height,"
                + "grossWeight,netWeight,img,category";
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        layout.put(LAYOUT_FORM_EDIT_FLDS, fieldStr);
        fieldStr = "id,coco,subcoco,materialId,materialCombId,serialNo,name,brand,shortDesc,description,stock,purchasePrice,costPrice,"
                + "supplyPrice,salePrice,salesChannel,packaging,length,width,height,"
                + "grossWeight,netWeight,img,category";
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);

        return layout;
    }

    private static Layout getProductMappingLayout() {
        Layout layout = new Layout();
        String fieldStr = "coco,subcoco,pfProductId,pfProName,productId";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);

        fieldStr = "coco,subcoco,pfProductId,pfProName,productId";
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        layout.put(LAYOUT_FORM_EDIT_FLDS, fieldStr);
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        return layout;
    }

    private static Layout getSOMappingLayout() {
        Layout layout = new Layout();
        String fieldStr = "platSOId,platForm,orderId";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);

        fieldStr = "platSOId,platForm,orderId";
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);

        return layout;
    }

    private static Layout getShopLayout() {
        Layout layout = new Layout();
        String fieldStr = "name";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        layout.put(LAYOUT_FORM_EDIT_FLDS, fieldStr);
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        return layout;
    }

    private static Layout getRoleLayout() {
        Layout layout = new Layout();
        String fieldStr = "";
        fieldStr = "id,coco,storeId,name,description";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);
        fieldStr = "coco,storeId,name,description,createdAt,createdBy";
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        fieldStr = "coco,storeId,name,description";
        layout.put(LAYOUT_FORM_EDIT_FLDS, fieldStr);
        fieldStr = "coco,storeId,name,description";
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        return layout;
    }

    private static Layout getStockLayout() {
        Layout layout = new Layout();
        String fieldStr = "id,coco,subcoco,name,stock";
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        fieldStr = "id,parentId,coco,subcoco,img,name,stock";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);
        fieldStr = "id,coco,subcoco,name,stock";
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        return layout;
    }

    private static Layout getStockHisLayout() {
        Layout layout = new Layout();
        String fieldStr = "deltaQty,updateAt,note,source,updateBy,status";
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);
        fieldStr = "deltaQty,status,note,source,updateAt,updateBy,createdAt,createdBy";
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        return layout;
    }

    private static Layout getSystemLogLayout() {
        Layout layout = new Layout();
        String fieldStr = "";
        fieldStr = "id,coco,logAction,logMessage,ipAddress,createdAt,createdBy";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);
        fieldStr = "id,coco,logAction,logMessage,ipAddress,createdAt,createdBy";
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        fieldStr = "id,coco,logAction,logMessage,ipAddress";
        layout.put(LAYOUT_FORM_EDIT_FLDS, fieldStr);
        fieldStr = "id,coco,logAction,logMessage,ipAddress,createdAt,createdBy";
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        return layout;
    }

    private static Layout getOrderSalLayout() {
        Layout layout = new Layout();
        String fieldStr = "";
        fieldStr = "coco,subcoco,number,salesChannel,orderNote,recName,recTel,recAddress,updateAt,status";
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        fieldStr = "coco,subcoco,number,salesChannel,recName,recTel,recAddress,updateAt,status";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);
        fieldStr = "coco,subcoco,number,orderNote,arrivalDate,salesChannel,expCompName,expNo,expType,recName,"
                + "recTel,recAddress,amount,status,updateAt,updateBy,createdAt,createdBy,orderItems";
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        return layout;
    }

    private static Layout getOrderSalHisLayout() {
        Layout layout = new Layout();
        String fieldStr = "";
        fieldStr = "updatedAt,orderNote,expCompName,expNo,status";
        layout.put(LAYOUT_TAB_DIS_FLDS, fieldStr);
        fieldStr = "number,orderNote,arrivalDate,salesChannel,expCompName,expNo,expType,"
                + "recName,recTel,recAddress,amount,memo,status,updatedAt,updatedBy";
        layout.put(LAYOUT_SEARCH_DIS_FLDS, fieldStr);
        layout.put(LAYOUT_FORM_DIS_FLDS, fieldStr);
        return layout;
    }

    private static Layout getOrderPurchHisLayout() {
        Layout layout = new Layout();
        String fieldStr = "";
        fieldStr = "updatedAt,orderNote,expCompName,expNo,status";
        layout.tableDisFld = fieldStr.split(",");
        fieldStr = "number,orderNote,arrivalDate,salesChannel,expCompName,expNo,expType,"
                + "recName,recTel,recAddress,amount,memo,status,updatedAt,updatedBy";
        layout.formDisFld = fieldStr.split(",");
        return layout;
    }

    private static Layout getOrderPurchLayout() {
        Layout layout = new Layout();
        String fieldStr = "";
        fieldStr = "number,orderNote,salesChannel,expCompName,expNo,status";
        layout.searchDisFld = fieldStr.split(",");
        fieldStr = "number,orderNote,expCompName,expNo,status";
        layout.tableDisFld = fieldStr.split(",");
        fieldStr = "number,orderNote,arrivalDate,salesChannel,expCompName,expNo,expType,"
                + "recName,recTel,recAddress,amount,status,updateAt,updateBy,createdAt,createdBy,orderItems";
        layout.formDisFld = fieldStr.split(",");
        return layout;
    }

    /******************Set Default Layouts ******************************/

    @SuppressWarnings("rawtypes")
    public static String getClsFieldStr(Class cls) {
        String fieldStr = "";
        // productLayout.put(LAYOUT_TAB_LIST_FLDS,
        // "number,serialNo,name,shortDesc");
        Field[] fields = cls.getDeclaredFields();
        for (int i = 0; i < fields.length; i++) {
            fieldStr += fields[i].getName() + ",";
        }
        if ("".equals(fieldStr)) {
            return null;
        } else {
            return fieldStr.substring(0, fieldStr.length() - 1);
        }
    }

    @SuppressWarnings("rawtypes")
    private static String getAuthTree(Class cls) {
        String str = "";
        String clsName = cls.getSimpleName();
        try {
            Field[] fields = cls.getDeclaredFields();
            for (int i = 0; i < fields.length; i++) {
                str += " { " + "'text': '', " + "'id'   : '" + UtilityTool.firstLowerCase(clsName) + "_field_"
                        + fields[i].getName() + "', " + "'state': { 'selected': false }, "
                        + "'icon': 'fa fa-file icon-state-success'," + " },";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return str;
    }
}
